package bod;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;

import bod.gui.Screen;

public class Progress {

	private static ArrayList<Job>	pendingJobs;
	private static int				currentJob;
	private static int				totalDone;
	private static int				totalWork;

	static {
		pendingJobs = new ArrayList<Job>();
		currentJob = -1;
		totalDone = 0;
		totalWork = 0;
	}

	public static void addJob(String name, int work, Runnable run) {
		pendingJobs.add(new Job(name, work, run));
		totalWork += work;
		if (currentJob == -1) {
			currentJob = 0;
			pendingJobs.get(currentJob).start();
		}
	}

	public static void done(int done) {
		if (isBusy()) {
			pendingJobs.get(currentJob).done(done);
			totalDone += done;
		}
	}

	public static boolean isBusy() {
		return totalDone < totalWork;
	}

	public static void tick() {
		if (isBusy()) {
			if (!pendingJobs.get(currentJob).isBusy()) {
				currentJob++;
				if (pendingJobs.size() == currentJob) {
					pendingJobs.clear();
					currentJob = -1;
					totalDone = 0;
					totalWork = 0;
				} else {
					pendingJobs.get(currentJob).start();
				}
			}
		}
	}

	public static void draw(Graphics g) {
		double prgs = totalDone * 1.0 / totalWork;
		int sw = Screen.getWidth();
		int sh = Screen.getHeight();
		g.setColor(Color.black);
		g.fillRect(0, 0, sw, sh);
		int imgw = 256;
		int imgh = 64;
		int imgs = sw / imgw + 1;
		int y = sh - imgh;
		int progressWidth = (int) (prgs * sw);
		for (int i = 0; i < imgs; i++) {
			int x = i * imgw;
			if (x < progressWidth) {
				int width = progressWidth - x;
				g.setClip(x, y, width, imgh);
				g.drawImage(Images.prgf, x, y, imgw, imgh, null);
				g.setClip(x + width, y, imgw - width, imgh);
				g.drawImage(Images.prge, x, y, imgw, imgh, null);
				g.setClip(0, 0, sw, sh);
			} else {
				g.drawImage(Images.prge, x, y, imgw, imgh, null);
			}
		}
		g.setColor(Color.white);
		String info1 = (int) (prgs * 100) + "%";
		g.drawString(info1, sw - g.getFontMetrics().stringWidth(info1), y);
		String info2 = pendingJobs.get(currentJob).getName() + "...";
		g.drawString(info2, 0, y);
	}

}